﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Net;
using System.Xml;
using System.IO;
using System.Web;
using GoGrid;

namespace Readify.Management.Automation.GoGrid
{
    [Cmdlet("Add", "GoGridLoadBalancer")]
    public class AddGoGridLoadBalancerCmdlet : GoGridCmdletBase
    {
        [Parameter(Mandatory = true)]
        public string Name { get; set; }

        [Parameter(Mandatory = true)]
        public string VirtualInterface { get; set; }

        [Parameter(Mandatory = true)]
        public string[] RealInterfaces { get; set; }

        [Parameter()]
        public string Description { get; set; }

        [Parameter()]
        public string Type { get; set; }

        [Parameter()]
        public string Persistence { get; set; }

        private LoadBalancerInterface ParseInterface(string input)
        {
            string[] parts = input.Split(':');
            string address = parts[0];
            int port = int.Parse(parts[1]);

            LoadBalancerInterface iface = new LoadBalancerInterface(address, port);
            return iface;
        }

        protected override void ProcessRecord()
        {
            Connection connection = this.GetConnection();

            LoadBalancerInterface virtualInterface = this.ParseInterface(this.VirtualInterface);

            List<LoadBalancerInterface> realInterfaces = new List<LoadBalancerInterface>();
            foreach (string realInterfaceString in this.RealInterfaces)
            {
                LoadBalancerInterface realInterface = this.ParseInterface(realInterfaceString);
                realInterfaces.Add(realInterface);
            }

            LoadBalancer balancer = connection.AddLoadBalancer(
                this.Name,
                virtualInterface,
                realInterfaces.ToArray(),
                new LoadBalancerType(this.Type),
                new LoadBalancerPersistence(this.Persistence),
                this.Description
                );

            this.WriteObject(balancer);
        }
    }
}
